/**
 * 
 */
package net.ddns.heroli.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.gzheroli.bfw.pojo.base.TSUser;
import cn.com.gzheroli.cache.SpringRedisCache;
import cn.com.gzheroli.core.common.model.json.AjaxJson;
import cn.com.gzheroli.core.common.model.json.TreeGrid;
import cn.com.gzheroli.core.common.service.CommonService;
import cn.com.gzheroli.core.common.service.HeroService;
import cn.com.gzheroli.core.common.service.SystemService;
import cn.com.gzheroli.core.manager.Client;
import cn.com.gzheroli.core.util.IdWorker;
import cn.com.gzheroli.core.util.NameHandler;
import cn.com.gzheroli.core.util.RequestUtil;
import cn.com.gzheroli.util.GenSqlUtil;
import net.ddns.heroli.model.GoodsModel;
import net.ddns.heroli.pojo.TBGoods;
import net.ddns.heroli.pojo.TBGoodsAttr;
import net.ddns.heroli.pojo.TBGoodsType;

/**  
* 类名: GoodsController  
* 描述: TODO(这里用一句话描述这个类的作用)  
* 作者: 李长荣 lichang_20011@163.com  
* 日期: 2017年12月18日  下午12:47:09
*@version V1.0  
*    
*/
@Controller
@RequestMapping("/api/goodsController")
public class GoodsController {
	private static final Logger logger = LoggerFactory.getLogger(GoodsController.class);
	@Autowired
	private CommonService commonService;
	@Autowired
	private HeroService heroService;
	@Autowired
    private SpringRedisCache cache;
	@Autowired
	private SystemService systemService;
	@RequestMapping(value = "getGood")
	@ResponseBody
	public AjaxJson getGood(String id, HttpServletRequest request) {
		
		AjaxJson j = new AjaxJson();
		if(id==null||id.trim().equals("")){
			j.setSuccess(false);
			j.setMsg("id不存在!");
			return j;
		}
		Map paras=new HashMap();
		paras.put("id", id);
		Map good=heroService.findForSqlIdSingle("goods.getGood", paras, Map.class);
		List goodsAttrList=heroService.findForSqlId("goods.getGoodAttrList",paras,Map.class);
		if(good!=null&&!good.isEmpty()) {
		good.put("goodsAttrList", goodsAttrList);
		}
		j.setObj(good);
		j.setSuccess(true);
		j.setMsg("删除成功!");
		return j;
	}
	@RequestMapping(value = "del")
	@ResponseBody
	public AjaxJson del(String id, HttpServletRequest request) {
		
		AjaxJson j = new AjaxJson();
		if(id==null||id.trim().equals("")){
			j.setSuccess(false);
			j.setMsg("id不存在!");
			return j;
		}
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		TSUser user=client.getUser();
		TBGoods goods=commonService.get(TBGoods.class, id);
		goods.setUpdateBy(user.getId());
		goods.setUpdateTime(new Date());
		goods.setUpdateByName(user.getRealName());
		goods.setStatus("0");
		commonService.update(goods);
		j.setSuccess(true);
		j.setMsg("删除成功!");
		return j;
	}
	/**
	 * 
	* @Title save 
	* @Description TODO(这里用一句话描述这个方法的作用) 
	* @param @param goods
	* @param @param goodsAttrs
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "save")
	@ResponseBody
	public  AjaxJson save(TBGoods goods, GoodsModel goodsModel, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		TSUser user=client.getUser();
		//TBGoods goods=goodsModel.getGoods();
		List<TBGoodsAttr> goodsAttrs=goodsModel.getGoodsAttrs();
		if(goods.getId()==null){
			String goodsId=IdWorker.getFlowIdWorkerInstance().nextIdStr();
			goods.setId(goodsId);
			goods.setUpdateBy(user.getId());
			goods.setUpdateTime(new Date());
			goods.setUpdateByName(user.getRealName());
			goods.setStatus("1");
			if(goodsAttrs!=null&&!goodsAttrs.isEmpty()) {
				for(TBGoodsAttr goodAttr:goodsAttrs) {
					goodAttr.setGoodsId(goodsId);
					goodAttr.setUpdateBy(user.getId());
					goodAttr.setUpdateTime(new Date());
					goodAttr.setUpdateByName(user.getRealName());
					goodAttr.setStatus("1");
					commonService.save(goodAttr);
				}
			}
			commonService.save(goods);
		}else{
			goods.setUpdateBy(user.getId());
			goods.setUpdateTime(new Date());
			goods.setUpdateByName(user.getRealName());
			commonService.update(goods);
			if(goodsAttrs!=null&&!goodsAttrs.isEmpty()) {
				for(TBGoodsAttr goodAttr:goodsAttrs) {
					if(goodAttr.getId()==null) {
						goodAttr.setGoodsId(goods.getId());
						goodAttr.setUpdateBy(user.getId());
						goodAttr.setUpdateTime(new Date());
						goodAttr.setUpdateByName(user.getRealName());
						//goodAttr.setStatus("1");
						commonService.save(goodAttr);
					}else {
						goodAttr.setGoodsId(goods.getId());
						goodAttr.setUpdateBy(user.getId());
						goodAttr.setUpdateTime(new Date());
						goodAttr.setUpdateByName(user.getRealName());
						//goodAttr.setStatus("1");
						commonService.update(goodAttr);
					}
				}
			}
		}
		j.setSuccess(true);
		j.setMsg("保存成功!");
		return j;
	}
	@RequestMapping(value = "update")
	@ResponseBody
	public  AjaxJson update( HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		String id=request.getParameter("id")==null?"":request.getParameter("id");
		TSUser user=client.getUser();
		if(id==null||id.trim().equals("")){
			j.setSuccess(false);
			j.setMsg("保存失败!,编号不能为空");
			return j;
		}else{
			Map reqMap=RequestUtil.convertParameterToMap(request);
			reqMap.put("updateBy", user.getId());
			reqMap.put("updateTime", new Date());
			reqMap.put("updateByName", user.getRealName());
			heroService.updateMap("T_B_GOODS", reqMap, null, TBGoods.class);
		}
		j.setSuccess(true);
		j.setMsg("保存成功!");
		return j;
	}
	@RequestMapping(value = "list")
	@ResponseBody
	public  AjaxJson  list(HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
		AjaxJson j = new AjaxJson();
		String page=request.getParameter("page")==null?"1":request.getParameter("page");
		String rows=request.getParameter("rows")==null?"1000":request.getParameter("rows");
		//Client client=cache.getCache(request.getSession().getId(), Client.class);
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			//return null;
		}else{
			TSUser user=client.getUser();
		}
		Map reqMap=RequestUtil.convertParameterToMap(request);
		List<Map<String,Object>> treeGrids = new ArrayList<Map<String,Object>>();
		Map conMap=new HashMap();
		conMap.put("status", "=");
		if(!reqMap.containsKey("status"))
			reqMap.put("status", "1");
		if(reqMap.containsKey("name"))
		conMap.put("name", "like");
		if(reqMap.containsKey("code"))
			conMap.put("code", "like");
		Class clazz=TBGoods.class;
		String tableName = new NameHandler().getTableName(clazz.getSimpleName());
		Map<String,Object> tableColumns=systemService.getHeroTableColumns(tableName,clazz);
		String whereSql="";
		whereSql=GenSqlUtil.genWhereSql(tableName, conMap, tableColumns, "g", reqMap);
		//Map<String,Object> userColumns=systemService.getHeroTableColumns("T_S_USER",TSUser.class);
		//whereSql=whereSql+GenSqlUtil.genWhereSql("T_S_USER", conMap, userColumns, "u", reqMap);
		List whereSqlList=new ArrayList();
		whereSqlList.add(" 1=1 "+whereSql);
		reqMap.put("whereSql", " 1=1 "+whereSql);
		PageQuery pg=heroService.findForSqlIdPage("goods.getGoodList", reqMap,Long.parseLong(page),Long.parseLong(rows));
		j.setObj(pg.getList());
		j.setTotal(pg.getTotalRow());
		return j;
	}
	
	@RequestMapping(value = "delGoodsAttr")
	@ResponseBody
	public AjaxJson delGoodsAttr(String id, HttpServletRequest request) {
		
		AjaxJson j = new AjaxJson();
		if(id==null||id.trim().equals("")){
			j.setSuccess(false);
			j.setMsg("id不存在!");
			return j;
		}
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		TSUser user=client.getUser();
		TBGoodsAttr goodsAttr=commonService.get(TBGoodsAttr.class, id);
		goodsAttr.setUpdateBy(user.getId());
		goodsAttr.setUpdateTime(new Date());
		goodsAttr.setUpdateByName(user.getRealName());
		goodsAttr.setStatus("0");
		commonService.update(goodsAttr);
		j.setSuccess(true);
		j.setMsg("删除成功!");
		return j;
	}
	@RequestMapping(value = "saveGoodsAttr")
	@ResponseBody
	public  AjaxJson saveGoodsAttr(TBGoodsAttr goodsAttr, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		TSUser user=client.getUser();
		if(goodsAttr.getId()==null){
			goodsAttr.setUpdateBy(user.getId());
			goodsAttr.setUpdateTime(new Date());
			goodsAttr.setUpdateByName(user.getRealName());
			goodsAttr.setStatus("1");
			commonService.save(goodsAttr);
		}else{
			goodsAttr.setUpdateBy(user.getId());
			goodsAttr.setUpdateTime(new Date());
			goodsAttr.setUpdateByName(user.getRealName());
			commonService.update(goodsAttr);
		}
		j.setSuccess(true);
		j.setMsg("保存成功!");
		return j;
	}
	@RequestMapping(value = "updateGoodsAttr")
	@ResponseBody
	public  AjaxJson updateGoodsAttr( HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		String id=request.getParameter("id")==null?"":request.getParameter("id");
		TSUser user=client.getUser();
		if(id==null||id.trim().equals("")){
			j.setSuccess(false);
			j.setMsg("保存失败!,编号不能为空");
			return j;
		}else{
			Map reqMap=RequestUtil.convertParameterToMap(request);
			reqMap.put("updateBy", user.getId());
			reqMap.put("updateTime", new Date());
			reqMap.put("updateByName", user.getRealName());
			heroService.updateMap("T_B_GOODS_ATTR", reqMap, null, TBGoodsAttr.class);
		}
		j.setSuccess(true);
		j.setMsg("保存成功!");
		return j;
	}
	@RequestMapping(value = "listGoodsAttr")
	@ResponseBody
	public  AjaxJson  listGoodsAttr(HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
		AjaxJson j = new AjaxJson();
		String page=request.getParameter("page")==null?"1":request.getParameter("page");
		String rows=request.getParameter("rows")==null?"1000":request.getParameter("rows");
		Map reqMap=RequestUtil.convertParameterToMap(request);
		List<Map<String,Object>> treeGrids = new ArrayList<Map<String,Object>>();
		Map conMap=new HashMap();
		conMap.put("status", "=");
		if(!reqMap.containsKey("status"))
			reqMap.put("status", "1");
		//if(reqMap.containsKey("projectType"))
		//conMap.put("projectType", "=");
		if(reqMap.containsKey("name"))
		conMap.put("name", "like");
		if(reqMap.containsKey("code"))
			conMap.put("code", "like");
		Class clazz=TBGoodsAttr.class;
		String tableName = new NameHandler().getTableName(clazz.getSimpleName());
		Map<String,Object> tableColumns=systemService.getHeroTableColumns(tableName,clazz);
		String sql=GenSqlUtil.genSqlByClass(clazz, conMap,"list",tableColumns,"am",reqMap);
		List beanList =commonService.findForJdbcPage(sql, clazz, reqMap, Integer.parseInt(page), Integer.parseInt(rows));
		j.setObj(beanList);
		String countSql=GenSqlUtil.genSqlByClass(clazz, conMap,"count",tableColumns,"am",reqMap);
		Long total=commonService.getCountForJdbc(countSql, reqMap);
		j.setTotal(total);
		return j;
	}
}
